﻿namespace SKeeper.Application.Services.Item
{
    using SKeeper.Domain.Repositories;
    using SKeeper.Persistence.Facade;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using SKeeper.Application.ViewModels.Items;
    using Persistence.Repositories;
    public class ItemControllerService : IItemControllerService
    {
        private DomainModelFacade db;

        private IItemRepository itemRepository;
        private ICompanyRepository companyRepository;

        public ItemControllerService(DomainModelFacade context)
        {
            this.db = context;
            this.itemRepository = new ItemRepository(this.db);
            this.companyRepository = new CompanyRepository(this.db);
        }

        public ItemIndexViewModel GetIndexViewModel(string userId)
        {
            var company = this.companyRepository.GetIncluding(x => x.Items)
                .First(x => x.UserId == userId);

            return new ItemIndexViewModel
            {
                CompanyId = company.Id,
                Items = company.Items.ToList().Select(x => ItemViewModel.FromItem(x))
            };            
        }

        public IEnumerable<ItemViewModel> GetAllItems(int companyId)
        {
            return this.itemRepository.GetAll().Where(x => x.CompanyId == companyId).ToList().Select(x => ItemViewModel.FromItem(x)).ToList();
        }

        public void CreateItem(ItemViewModel model)
        {
            Domain.Items.Item item = model.ToItem();
            this.itemRepository.Create(item);
            this.itemRepository.SaveChanges();
        }

        public void Add(ItemViewModel item)
        {
            itemRepository.Create(new Domain.Items.Item { Name = item.Name, CompanyId = item.CompanyId, Tax = item.Tax, Type = item.Type, Unit = item.Unit });
        }
    }
}
